import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Layout from "../components/Layout.vue";
import Home from "../components/Home.vue";
import About from "../components/About.vue";
import User from "../components/User.vue";
import NotFound from "../components/NotFound.vue";
import Login from "../components/Login.vue";
import { hasLogin } from "../utils/login";

const routes: RouteRecordRaw[] = [
  { path: "/:pathMatch(.*)*", name: "NotFound", component: NotFound },
  { path: "/login", name: "login", component: Login },
  {
    path: "/",
    component: Layout,
    redirect: "home",
    children: [
      {
        path: "home",
        name: "myhome",
        component: Home,
      },
      {
        path: "user/:uname",
        name: "user",
        component: User,
      },
      {
        path: "about",
        name: "about",
        component: About,
      },
    ],
  },
  // {
  //   path: "/:pathMatch(.*)*",
  //   name: "NotFound",
  //   component: NotFound,
  // },
];

export const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from) => {
  console.log("to = ", to);
  if (hasLogin()) {
    if (to.name === "login") {
      let toFulPath = "/";
      if (to.query.redirect) {
        toFulPath = to.query.redirect as string;
      }
      return { path: toFulPath };
    } else {
      return true;
    }
  } else {
    if (to.name === "login") {
      return true;
    } else {
      return {
        name: "login",
        query: { redirect: to.fullPath },
      };
    }
  }
  return true;
});
